<template>
  <div>
    <el-upload
  class="avatar-uploader"
  :action="uploadImgUrl"
  :show-file-list="false"
  :headers="headers"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

 export default {
  props:{avatar:String},
    data() {
      return {
        imageUrl: '',
        uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers: {
        Authorization: "Bearer " + getToken(),
      },
      };
    },
    watch: {
      avatar(n, o) {
      //n为新值,o为旧值;
      this.imageUrl = n
    }
  },
    created() {
      console.log(this.avatar)
      
      this.avatar = this.imageUrl
    },
    methods: {
      handleAvatarSuccess(res, file) {
        console.log(res)
        // this.imageUrl = URL.createObjectURL(file.raw);
        if (res.code === 200) {
            this.imageUrl = res.url
            this.$emit('imageUrl', res.url)
      } else {
        
        this.$modal.msgError(res.msg);
      
      }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/jpg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 240px;
    height: 300px;
    display: block;
  }
</style>